#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
uWSGI 测试应用
用于验证 uWSGI Exporter 的指标收集功能
"""

from flask import Flask, jsonify, request
import time
import random
import os

app = Flask(__name__)

# 全局计数器
request_count = 0
exception_count = 0

@app.route('/')
def index():
    """主页"""
    global request_count
    request_count += 1
    
    return jsonify({
        'message': 'uWSGI Test Application',
        'version': '1.0.0',
        'request_count': request_count,
        'timestamp': time.time()
    })

@app.route('/api/health')
def health():
    """健康检查"""
    return jsonify({
        'status': 'healthy',
        'timestamp': time.time()
    })

@app.route('/api/error')
def error():
    """模拟错误"""
    global exception_count
    exception_count += 1
    
    # 随机抛出异常
    if random.random() < 0.3:
        raise Exception("Simulated error for testing")
    
    return jsonify({
        'message': 'Error endpoint called',
        'exception_count': exception_count
    })

@app.route('/api/slow')
def slow():
    """模拟慢请求"""
    # 随机延迟 1-5 秒
    delay = random.uniform(1, 5)
    time.sleep(delay)
    
    return jsonify({
        'message': 'Slow request completed',
        'delay': delay
    })

@app.route('/api/stats')
def stats():
    """应用统计信息"""
    return jsonify({
        'request_count': request_count,
        'exception_count': exception_count,
        'uptime': time.time() - app.start_time if hasattr(app, 'start_time') else 0,
        'memory_usage': os.getpid()
    })

@app.route('/api/load')
def load():
    """模拟负载"""
    # 模拟CPU密集型操作
    start_time = time.time()
    result = 0
    for i in range(1000000):
        result += i * i
    
    processing_time = time.time() - start_time
    
    return jsonify({
        'result': result,
        'processing_time': processing_time
    })

@app.errorhandler(Exception)
def handle_exception(e):
    """异常处理器"""
    global exception_count
    exception_count += 1
    
    return jsonify({
        'error': str(e),
        'exception_count': exception_count
    }), 500

# 初始化启动时间
app.start_time = time.time()

if __name__ == '__main__':
    # 开发模式运行
    app.run(debug=True, host='0.0.0.0', port=5000)
else:
    # uWSGI 模式运行
    app.start_time = time.time() 